package com.zx.util;

import com.alibaba.fastjson.JSON;
import com.zx.constant.AuthorityConstant;
import com.zx.model.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Calendar;

/**
 * <h1>JWT Token 解析工具类</h1>
 * */
public class TokenParseUtil {

    /**
     * <h2>从 JWT Token 中解析 LoginUserInfo 对象</h2>
     * */
    public static LoginUserInfo parseUserInfoFromToken(String token) throws Exception {
        if (null == token) {
            return null;
        }
        Jws<Claims> claimsJws = parseToken(token, getPublicKey());
        Claims body = claimsJws.getBody();
        // 如果 Token 已经过期了, 返回 null
        if (body.getExpiration().before(Calendar.getInstance().getTime())) {
            return null;
        }
        // 返回 Token 中保存的用户信息
        return JSON.parseObject(
                body.get(AuthorityConstant.ECOMMERCE_USER_KEY).toString(),
                LoginUserInfo.class
        );
    }
    /**
     * <h2>通过公钥去解析 JWT Token</h2>
     * */
    private static Jws<Claims> parseToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * <h2>根据本地存储的公钥获取到 PublicKey 对象</h2>
     * */
    private static PublicKey getPublicKey() throws Exception {
//        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
//                new BASE64Decoder().decodeBuffer(CommonConstant.PUBLIC_KEY)
//        );
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                Base64.getDecoder().decode(AuthorityConstant.PUBLIC_KEY)
        );
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }

    public static void main(String[] args) throws Exception {
        LoginUserInfo loginUserInfo = parseUserInfoFromToken("eyJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2ODE2OTgzOTYsImV4cCI6MTY4MTg3MTE5NiwiZWNvbW1lcmNlX3VzZXIiOiJ7XCJpZFwiOjEsXCJ1c2VybmFtZVwiOlwiMTg2Mjc5Njc2MjBAMTYzLmNvbVwifSJ9.VGQNjGTmc_vI5PnUzPUl8hZaEdfA5DLOqpSjGWeL-FdhWVxmjwUCb5c2ygctQQ29od5wyDEAaYLeKgnJWloZUqdxqbNdTYn0n3qqZfTrW4ulP2eCgger-FK713KWWiUyooCrXzSlRV30ryOLXUhuA-nmOgQ9goVxq9FCPuguVhz4cgTwtG3G_uc_2pMjkxCmo8O-iEpc6G5GBGnRqc0X182P9geFTJib2wTX8qk7yrlSvw3bFvJRWqcUZkSssAgBJ7S-MfTle4_4YK7a1YwckY_nhGB6VHCsNpL--8-4c3lkpBOOxx19Hgw7Rai90hZOwTcOs91mx21T2-F92cCCpg");
        System.out.println(loginUserInfo);
    }
}
